/**
 * 需求卡片组件
 */
class DemandCard {
    constructor(demand, urgencyLevels, demandTypes) {
        this.demand = demand;
        this.urgencyLevels = urgencyLevels;
        this.demandTypes = demandTypes;
    }
    
    /**
     * 计算紧急程度
     */
    calculateUrgency() {
        if (!this.demand.deadline) {
            return { level: 'low', color: '#6c757d', label: '低优先级', days: null };
        }
        
        const deadline = new Date(this.demand.deadline);
        const now = new Date();
        const diffTime = deadline - now;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        // 根据紧急度配置计算
        for (const level of this.urgencyLevels.sort((a, b) => a.days - b.days)) {
            if (diffDays <= level.days) {
                return {
                    level: level.name.toLowerCase(),
                    color: level.color,
                    label: level.name,
                    days: diffDays
                };
            }
        }
        
        return { level: 'low', color: '#6c757d', label: '低优先级', days: diffDays };
    }
    
    /**
     * 格式化截止日期
     */
    formatDeadline() {
        if (!this.demand.deadline) {
            return '';
        }
        
        const deadline = new Date(this.demand.deadline);
        const now = new Date();
        const diffTime = deadline - now;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        if (diffDays < 0) {
            return `已逾期 ${Math.abs(diffDays)} 天`;
        } else if (diffDays === 0) {
            return '今天截止';
        } else if (diffDays === 1) {
            return '明天截止';
        } else {
            return `还有 ${diffDays} 天`;
        }
    }
    
    /**
     * 获取状态显示文本
     */
    getStatusText() {
        const statusMap = {
            'pending': '待处理',
            'in_progress': '进行中',
            'completed': '已完成',
            'rejected': '已拒绝'
        };
        
        return statusMap[this.demand.status] || this.demand.status;
    }
    
    /**
     * 渲染卡片HTML
     */
    render() {
        const urgency = this.calculateUrgency();
        const demandType = this.demandTypes[this.demand.demandType];
        const deadlineText = this.formatDeadline();
        const statusText = this.getStatusText();
        
        // 计算进度
        const progress = this.demand.workflow ? 
            window.workflowEngine.getWorkflowProgress(this.demand.workflow) : 0;
        
        return `
            <div class="demand-card ${urgency.level}" data-demand-id="${this.demand.id}">
                <div class="demand-header">
                    <h3 class="demand-title">${this.escapeHtml(this.demand.title)}</h3>
                    <span class="demand-type" style="background-color: ${demandType?.color || '#6c757d'}20; color: ${demandType?.color || '#6c757d'}">
                        ${demandType?.icon || '📋'} ${demandType?.name || this.demand.demandType}
                    </span>
                </div>
                
                ${this.demand.description ? `
                    <div class="demand-description">
                        ${this.escapeHtml(this.demand.description)}
                    </div>
                ` : ''}
                
                <div class="demand-meta">
                    <span class="demand-status ${this.demand.status}">
                        ${statusText}
                    </span>
                    <div class="urgency-indicator ${urgency.level}">
                        <span class="urgency-dot ${urgency.level}"></span>
                        ${urgency.label}
                    </div>
                </div>
                
                ${this.demand.deadline ? `
                    <div class="demand-deadline ${urgency.days !== null && urgency.days <= 1 ? 'overdue' : urgency.days <= 3 ? 'soon' : ''}">
                        ⏰ ${deadlineText}
                    </div>
                ` : ''}
                
                <div class="demand-progress">
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${progress}%"></div>
                    </div>
                    <div class="progress-text">进度: ${progress}%</div>
                </div>
                
                ${this.demand.tags && this.demand.tags.length > 0 ? `
                    <div class="demand-tags">
                        ${this.demand.tags.map(tag => `
                            <span class="demand-tag">${this.escapeHtml(tag)}</span>
                        `).join('')}
                    </div>
                ` : ''}
                
                <div class="demand-footer">
                    <div class="demand-assignee">
                        ${this.getCurrentAssignee()}
                    </div>
                    <div class="demand-actions">
                        <button class="demand-action primary" onclick="app.viewDemandDetails('${this.demand.id}')">
                            查看详情
                        </button>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 获取当前负责人
     */
    getCurrentAssignee() {
        if (!this.demand.workflow) {
            return '未分配';
        }
        
        const currentNode = window.workflowEngine.getCurrentNode(this.demand.workflow);
        if (!currentNode) {
            return '流程已完成';
        }
        
        return `👤 ${currentNode.defaultAssignee || '待分配'}`;
    }
    
    /**
     * HTML转义
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 导出到全局
window.DemandCard = DemandCard;